#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2024-07-09 12:59:47
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   mysql数据库连接
'''
from contextlib import asynccontextmanager

from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession

from app.config import config

database_config = config.database

DB_URL = "mysql+aiomysql://{}:{}@{}:{}/{}?charset=utf8mb4".format(database_config.username, 
                                                                 database_config.password, 
                                                                 database_config.host, 
                                                                 database_config.port, 
                                                                 database_config.database_name) 
engine = create_async_engine(
    DB_URL, 
    echo=True,
    pool_size=database_config.pool_size,
    max_overflow=database_config.max_overflow,
)  

Session = sessionmaker(
    bind=engine, 
    expire_on_commit=False,
    class_=AsyncSession) # type: ignore

@asynccontextmanager # type: ignore
async def getDatabaseSession(autoCommitByExit=True) -> AsyncSession: # type: ignore
    """" 获取数据库session对象，自动关闭session对象"""
    async with Session() as _session: # type: ignore
        try:
            yield _session # type: ignore
            # 退出时，是否自动提交
            if autoCommitByExit:
                await _session.commit() # type: ignore

        except Exception as e:
            await _session.rollback() # type: ignore
            raise e 
        
        finally:
            await _session.close() # type: ignore


__all__ = ["getDatabaseSession"]